1
|
|
|
"use strict"; |
2
|
|
|
|
3
|
|
|
const WebSocket = require("ws"); |
4
|
|
|
|
5
|
|
|
const handleProtocols = (protocols /*, request */ ) => { |
6
|
|
|
console.info(`Incoming protocol requests '${protocols}'.`); |
7
|
|
|
for (var i = 0; i < protocols.length; i++) { |
8
|
2 |
|
if (protocols[i] === "text") { |
9
|
|
|
return "text"; |
10
|
2 |
|
} else if (protocols[i] === "json") { |
11
|
|
|
return "json"; |
12
|
|
|
} |
13
|
|
|
} |
14
|
|
|
return false; |
15
|
|
|
}; |
16
|
|
|
|
17
|
|
|
let makeWss = (server) => { |
18
|
|
|
const wss = new WebSocket.Server({ |
19
|
|
|
server: server, |
20
|
|
|
clientTracking: true, // keep track on connected clients |
21
|
|
|
handleProtocols: handleProtocols |
22
|
|
|
}); |
23
|
|
|
|
24
|
|
|
return wss; |
25
|
|
|
}; |
26
|
|
|
|
27
|
|
|
let socket = (server) => { |
28
|
|
|
|
29
|
|
|
const wss = makeWss(server); |
30
|
|
|
|
31
|
|
|
wss.broadcastExcept = (ws, data) => { |
32
|
|
|
let clients = 0; |
33
|
|
|
|
34
|
|
|
wss.clients.forEach((client) => { |
35
|
4 |
|
if (client !== ws && client.readyState === WebSocket.OPEN) { |
36
|
|
|
clients++; |
37
|
2 |
|
if (ws.protocol === "json") { |
38
|
|
|
let msg = { |
39
|
|
|
data: data |
40
|
|
|
}; |
41
|
|
|
|
42
|
|
|
client.send(JSON.stringify(msg)); |
43
|
|
|
} else { |
44
|
|
|
client.send(data); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
}); |
48
|
|
|
console.info(`Broadcasted data to ${clients} (${wss.clients.size}) clients.`); |
49
|
|
|
}; |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
|
53
|
|
|
// Setup for websocket requests. |
54
|
|
|
// Docs: https://github.com/websockets/ws/blob/master/doc/ws.md |
55
|
|
|
wss.on("connection", (ws /*, req*/ ) => { |
56
|
|
|
console.info("Connection received. Adding client."); |
57
|
|
|
|
58
|
|
|
// wss.broadcastExcept(ws, `New client connected (${wss.clients.size}).`); |
59
|
|
|
|
60
|
|
|
ws.on("message", (message) => { |
61
|
|
|
// console.log("Received: %s", message); |
62
|
|
|
wss.broadcastExcept(ws, message); |
63
|
|
|
}); |
64
|
|
|
|
65
|
|
|
ws.on("error", (error) => { |
66
|
|
|
console.error(`Server error: ${error}`); |
67
|
|
|
}); |
68
|
|
|
|
69
|
|
|
ws.on("close", (code, reason) => { |
70
|
|
|
console.info(`Closing connection: ${code} ${reason}`); |
71
|
|
|
// wss.broadcastExcept(ws, `Client disconnected (${wss.clients.size}).`); |
72
|
|
|
}); |
73
|
|
|
}); |
74
|
|
|
}; |
75
|
|
|
|
76
|
|
|
module.exports = { |
77
|
|
|
socket: socket |
78
|
|
|
}; |
79
|
|
|
|